package chapters15_bingfa.chapters15_3;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * Created by xinxuchu on 2020/1/27.
 * 生产者/消费者模式
 */
public class MyBlockingQueue <E> {
    private Queue<E> queue = null;
    private int limit;

    public MyBlockingQueue(int limit) {
        this.limit = limit;
        queue = new ArrayDeque<>(limit);
    }

    public synchronized void put(E e) throws InterruptedException{
        while (queue.size() == limit){//满了的话 wait  ，生产者生产数据
            wait();
        }
        queue.add(e);
        notifyAll();
    }

    public synchronized E take() throws InterruptedException{
        while (queue.isEmpty()){//空了的话，wait ，消费者是拿数据
            wait();
        }
        E e = queue.poll();
        notifyAll();
        return e;
    }

}
